package com.syh.jn.scm.infrastructure.repository.impl.operation.supplier;

import cn.redscarf.commons.util.bean.ExtBeanUtils;
import cn.redscarf.commons.util.other.ExtAssert;
import com.syh.core.ddd.infrastructure.repository.AbstractAggregateRepository;
import com.syh.core.expction.DataModelException;
import com.syh.jn.scm.domain.operation.entity.supplier.OperaSupplierAccount;
import com.syh.jn.scm.domain.operation.repository.supplier.OperaSupplierAccountReadRepository;
import com.syh.jn.scm.infrastructure.repository.model.system.AccountModel;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import java.math.BigInteger;
import java.util.List;

@Repository
public class OperaSupplierAccountReadRepositoryImpl extends AbstractAggregateRepository<OperaSupplierAccount, AccountModel, Long> implements OperaSupplierAccountReadRepository {

  /**
   * 添加供应商账号
   *
   * @param account
   * @return
   */
  @Override
  public Boolean addAccount(OperaSupplierAccount account) {
    ExtAssert.notNull(account, "对象为空");
    StringBuffer hql = new StringBuffer();
    hql.append("from AccountModel model where model.businessEntityId = ? and model.terminalType = 'SUPPLIER' and model.admin = 1");
    List<AccountModel> modelList = (List<AccountModel>) this.hibernateTemplate.find(hql.toString(), account.getBusinessEntityId());
    if (modelList != null && modelList.size() > 0) {
      throw new DataModelException("该供应商已开通帐号!");
    }
    AccountModel accountModel = AccountModel.builder()
            .terminalType("SUPPLIER")
            .build();
    ExtBeanUtils.copyProperties(account, accountModel, false);
    accountModel.setRoleId(0l);
    accountModel.setAdmin(Short.valueOf("1"));
    accountModel.setName("管理员");
    super.hibernateTemplate.save(accountModel);
    return Boolean.TRUE;
  }

  @Override
  public Short getAdminById(Long id) {
    AccountModel model = this.hibernateTemplate.get(AccountModel.class, id);
    if (model != null) {
      return model.getAdmin();
    }
    return null;
  }

  @Override
  public Long getCountByAccountName(String accountName) {
    String hql = "select count(*) from AccountModel model where model.loginAccount = :accountName";
    Query query = this.buildQuery(hql);
    query.setString("accountName", accountName);

    return (Long) query.uniqueResult();
  }

  @Override
  public Long getCountByAccountName(String accountName, Long excludeId) {
    String hql = "select count(*) from AccountModel model where model.loginAccount = :accountName and model.id !=:excludeId";
    Query query = this.buildQuery(hql);
    query.setString("accountName", accountName);
    query.setBigInteger("excludeId",BigInteger.valueOf(excludeId));

    return (Long) query.uniqueResult();
  }
}
